package com.shanghai.shanghaielectric;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shanghai.shanghaielectric.DB.LitePalHelper;
import com.shanghai.shanghaielectric.DB.SharepreferenceUtil;
import com.shanghai.shanghaielectric.DataAdapter.Cells2ShowAdapter;
import com.shanghai.shanghaielectric.DataAdapter.ReportDataHelper;
import com.shanghai.shanghaielectric.Model.CapacityCuttingModel;
import com.shanghai.shanghaielectric.Model.DeviceState;
import com.shanghai.shanghaielectric.Model.EventBus.EventbusModel_Tag;
import com.shanghai.shanghaielectric.Model.EventBus.EventbusModel_Toast;
import com.shanghai.shanghaielectric.Model.EventBus.EventbusModel_debugButton_state;
import com.shanghai.shanghaielectric.Model.EventBus.EventbusModel_setting_debug_state;
import com.shanghai.shanghaielectric.Model.ReceiveDataModel;
import com.shanghai.shanghaielectric.Model.ReportDateModel;
import com.shanghai.shanghaielectric.Model.WarningInfoModel;
import com.shanghai.shanghaielectric.Model.WriteDataModel;
import com.shanghai.shanghaielectric.Model.db.ErrorInfoModel;
import com.shanghai.shanghaielectric.Model.db.OperateInfoModel;
import com.shanghai.shanghaielectric.Model.db.ReceiveDataModel_10s;
import com.shanghai.shanghaielectric.Model.db.ReportDateModel_1day;
import com.shanghai.shanghaielectric.UI.Active_reActiveFragment;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_Alert;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_Password;
import com.shanghai.shanghaielectric.UI.KeyBoard.MKeyBoard_NumberInput;
import com.shanghai.shanghaielectric.UI.MonitorBasicFragment;
import com.shanghai.shanghaielectric.UI.MonitorUnitFragment;
import com.shanghai.shanghaielectric.UI.ScanFragment;
import com.shanghai.shanghaielectric.UI.chart.ChartDatabaseFragment;
import com.shanghai.shanghaielectric.UI.debug.DebuggingFragment;
import com.shanghai.shanghaielectric.UI.event.EventFragment;
import com.shanghai.shanghaielectric.UI.setting.SettingFragment;
import com.shanghai.shanghaielectric.excel.ExcelHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;
import org.litepal.LitePalDB;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import shanghaielectric_lib.Communication.Comm_Modbus.ModbusThread;
import shanghaielectric_lib.Communication.CommunicateManager;
import shanghaielectric_lib.EnumDataHelper;
import shanghaielectric_lib.MyEventBus.EventBus_int_bool;
import shanghaielectric_lib.MyEventBus.EventBus_showCells;
import shanghaielectric_lib.RDBHelper.Cell_show;
import shanghaielectric_lib.Utils.FileUtils.TxtUtil;
import shanghaielectric_lib.Utils.LogUtil;
import shanghaielectric_lib.Utils.MySystemUtil;
import shanghaielectric_lib.Utils.dwin.Dwin;

public class MainActivity extends FragmentActivity {
    @BindView(R.id.main_logo)
    ImageView mainLogo;
    @BindView(R.id.tv_system_time)
    TextView tvSystemTime;
    @BindView(R.id.test_btn)
    Button testBtn;
    @BindView(R.id.bt_reset)
    Button btReset;
    @BindView(R.id.bt_device_start)
    Button bt_device_start;
    @BindView(R.id.connunication_btn)
    ImageView connunicationBtn;
    @BindView(R.id.wifi_btn)
    ImageView wifiBtn;
    @BindView(R.id.date_btn)
    TextView dateBtn;
    @BindView(R.id.exit)
    LinearLayout exit;
    @BindView(R.id.bt_home)
    Button btHome;
    @BindView(R.id.bt_event)
    Button btEvent;
    @BindView(R.id.bt_debug)
    Button btDebug;
    @BindView(R.id.bt_set)
    Button btSet;
    @BindView(R.id.bt_thd)
    Button btThd;
    @BindView(R.id.bt_unit_1)
    Button btUnit1;
    @BindView(R.id.bt_unit_2)
    Button btUnit2;
    @BindView(R.id.bt_unit_3)
    Button btUnit3;
    @BindView(R.id.bt_unit_4)
    Button btUnit4;
    @BindView(R.id.bt_unit_5)
    Button btUnit5;
    @BindView(R.id.bt_unit_6)
    Button btUnit6;
    @BindView(R.id.bt_unit_7)
    Button btUnit7;
    @BindView(R.id.bt_unit_8)
    Button btUnit8;
    @BindView(R.id.tabs_main_rg)
    LinearLayout tabsMainRg;
    @BindView(R.id.bt_refresh_communicating)
    Button btRefreshCommunicating;
    @BindView(R.id.toplv)
    LinearLayout toplv;
    @BindView(R.id.tab_main_content)
    FrameLayout tabMainContent;
    @BindView(R.id.home_bar)
    LinearLayout homeBar;
    @BindView(R.id.systemState)
    Button systemState;
    private Context mContext = null;
    public List<Fragment> mainFragments = new ArrayList<Fragment>();
    private MonitorUnitFragment monitorUnitFragment;
    private MonitorBasicFragment monitorBasicFragment;
    List<Button> bt_list;
    List<Button> bt_list_unit;
    public int currentTab = 0;
    boolean[] deviceCommunicateState;
    private ModbusThread modbusThread;
    Cells2ShowAdapter cells2ShowAdapter;
    private long lastLoginTime = 0;
    //    private long lastTouchTime = System.currentTimeMillis();
    private static final int SAVE_REPORT_DATA = 110;
    private static final int SAVE_REPORT_DATA_PEROID = 10000;
    private static final int PUSH_DATE_TO_SERVICE = 211;
    private static final int PUSH_DATE_TO_SERVICE_PEROID = 10000;
    private final Timer timer = new Timer();
    private TimerTask timerTask;

    private ReportDateModel reportDateModelCurrentValue;//存储当前数据
    private ReceiveDataModel receiveDataModelCurrentValue;//存储当前数据


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mContext = MyApplication.getContext();
        //加上这句设置为全屏 不加则只隐藏title
        //横屏正方向

        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)


            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);

        initView();
        initData();
        setSelect(0);
        Dwin.getInstance().closeBar();
//        Dwin.getInstance().showBar();
        MySystemUtil.setNavigationState(true);
        modbusThread = new ModbusThread();
        modbusThread.start();

        initLitepal2();

    }

    private void initLitepal2() {
        LitePalDB litePalDB = new LitePalDB("DATA_APF", 1);
        litePalDB.addClassName(ErrorInfoModel.class.getName());
        litePalDB.addClassName(WarningInfoModel.class.getName());
        litePalDB.addClassName(OperateInfoModel.class.getName());
        litePalDB.addClassName(ReportDateModel.class.getName());
        litePalDB.addClassName(ReceiveDataModel_10s.class.getName());
        litePalDB.addClassName(CapacityCuttingModel.class.getName());
        litePalDB.addClassName(ReportDateModel.class.getName());
        litePalDB.addClassName(ReportDateModel_1day.class.getName());
        litePalDB.setExternalStorage(true);
        litePalDB.setStorage(Environment.getExternalStorageDirectory().getAbsolutePath() + "/hello");//适配APF屏
        LitePal.use(litePalDB);
    }

    public void initView() {
        bt_list = new ArrayList<>();
        bt_list.add(btHome);
        bt_list.add(btHome);
        bt_list.add(btDebug);
        bt_list.add(btSet);
        bt_list.add(btEvent);
        bt_list.add(btThd);
        bt_list.add(btUnit1);
        bt_list.add(btUnit2);
        bt_list.add(btUnit3);
        bt_list.add(btUnit4);
        bt_list.add(btUnit5);
        bt_list.add(btUnit6);
        bt_list.add(btUnit7);
        bt_list.add(btUnit8);
        bt_list.add(systemState);
        bt_list_unit = new ArrayList<>();
        bt_list_unit.add(btUnit1);
        bt_list_unit.add(btUnit2);
        bt_list_unit.add(btUnit3);
        bt_list_unit.add(btUnit4);
        bt_list_unit.add(btUnit5);
        bt_list_unit.add(btUnit6);
        bt_list_unit.add(btUnit7);
        bt_list_unit.add(btUnit8);
    }

    public void initData() {
        Constants.writeDataModel = SharepreferenceUtil.getObject(MyApplication.getContext(), WriteDataModel.class.getName());
        cells2ShowAdapter = new Cells2ShowAdapter();
        EventBus.getDefault().register(this);
        initDeviceState();
//        Constants.USER_PASSWORDS = String.valueOf(SharepreferenceUtil.get(mContext, "user_psd", Constants.USER_PASSWORDS));
        monitorUnitFragment = new MonitorUnitFragment();
        mainFragments.add(new ScanFragment());
        mainFragments.add(new MonitorBasicFragment());
        mainFragments.add(new DebuggingFragment());
        mainFragments.add(new SettingFragment());
        mainFragments.add(new EventFragment());
        mainFragments.add(new ChartDatabaseFragment());
        mainFragments.add(monitorUnitFragment);
        mainFragments.add(new Active_reActiveFragment());
//        Constants.setParameterModel = SharepreferenceUtil.getObject(mContext, "ParameterModel");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    EventBus.getDefault().post(MySystemUtil.getSystemTime());
//                    EventBus.getDefault().post(new ReportDateModel());
                    try {
                        Thread.sleep(1000);
                        checkLoginTime();

// 每小时的00:10开始 从10s表里取上一小时数据计算
//                        if (Calendar.getInstance().get(Calendar.MINUTE) == 55 && (Calendar.getInstance().get(Calendar.SECOND) == 10))
                        if ((Calendar.getInstance().get(Calendar.SECOND) == 10)) {
                            //执行开启线程 进行计算、存储


                            LitePalHelper.insertReportDateTo_1h();
                        }
// 每天的00:00:30开始 从1H表里取上一天数据计算
//                        if (Calendar.getInstance().get(Calendar.HOUR) == 0 && Calendar.getInstance().get(Calendar.MINUTE) == 0 && (Calendar.getInstance().get(Calendar.SECOND) == 30)) {
                        if (Calendar.getInstance().get(Calendar.MINUTE) == 4 && (Calendar.getInstance().get(Calendar.SECOND) == 23)) {

                            //执行开启线程 进行计算、存储
                            LitePalHelper.insertReportDateTo_1day();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        timerTask = new TimerTask() {
            @Override
            public void run() {
//10s 存一次通信值
                if (receiveDataModelCurrentValue != null) {
                    LitePalHelper.insertReceiveDataModel_10s(ReportDataHelper.getReceiveDataModel_10s(receiveDataModelCurrentValue));
                    Log.e("sheet", "开始插入" + Environment.getExternalStorageDirectory().getPath());
                    ExcelHelper.insertCapacitorCuttingRecord();
                    TxtUtil.writeLogToFile2(Environment.getExternalStorageDirectory().getPath(), "运行日志", "通信正常");


                }
            }
        };

        timer.schedule(timerTask, SAVE_REPORT_DATA_PEROID, SAVE_REPORT_DATA_PEROID);//10执行一次
    }


    private void checkLoginTime() {
        if (System.currentTimeMillis() - lastLoginTime > Constants.OUTLOGINTIME) {
            if (currentTab == 2 | currentTab == 3) {
                EventbusModel_Tag eventbusModel_tag = new EventbusModel_Tag();
                eventbusModel_tag.tag = EventbusModel_Tag.FRAGMENT_GOTO_1;
                EventBus.getDefault().post(eventbusModel_tag);
            }
        }
    }

    private void initDeviceState() {
        for (int i = 0; i < 8; i++) {
            DeviceState deviceState = new DeviceState();
            deviceState.id = i + 1;
            deviceState.isConnect = false;
            deviceState.enableState = false;
            deviceState.deviceState = DeviceState.deviceState_error;
            Constants.deviceStates[i] = deviceState;
        }
    }

    public void setTable(int i) {
        if (i == 2 | i == 3) {
            if (System.currentTimeMillis() - lastLoginTime > Constants.OUTLOGINTIME) {
                final int finalI = i;
                //输入密码
                MKeyBoard_NumberInput mKeyBoardInputValue = new MKeyBoard_NumberInput();
                mKeyBoardInputValue.setKeyBoardType(MKeyBoard_NumberInput.PSD);
                mKeyBoardInputValue.show(mainFragments.get(0).getFragmentManager(), "");
                mKeyBoardInputValue.setMkeyBoardListener(new MKeyBoard_NumberInput.MkeyBoardListener_numberKeyBoard() {
                    @Override
                    public void onClink(boolean isCorrect, String value) {
                        if (isCorrect) {
                            setSelect(finalI);
                            lastLoginTime = System.currentTimeMillis();
                        }
                    }
                });
            } else {
                setSelect(i);
            }
        } else {
            setSelect(i);
        }
    }

    public void setSelect(int i) {
        currentTab = i;
//        Constants.isSettingParameter = (currentTab == 4);
//        LogUtil.e("isSettingParameter" + Constants.isSettingParameter);
        FragmentManager fm = getSupportFragmentManager();
        final FragmentTransaction transaction = fm.beginTransaction();//创建一个事务
        hideFragment(transaction);//我们先把所有的Fragment隐藏了，然后下面再开始处理具体要显示的Fragment
        if (i == 0) {
            homeBar.setVisibility(View.GONE);
        } else {
            homeBar.setVisibility(View.VISIBLE);
            refreshButtonBackground(i);
        }
        if (i == 14) {
            if (mainFragments.get(7).isAdded()) {
                mainFragments.get(7).onResume();
            } else {
                transaction.add(R.id.tab_main_content, mainFragments.get(7));
            }
            transaction.show(mainFragments.get(7));
            transaction.commit();
        } else {
            if (i >= 6) {
                // unit button
                int deviceID = i - 5;
                i = 6;
                if (mainFragments.get(i).isAdded()) {
                    mainFragments.get(i).onResume();
                } else {
                    transaction.add(R.id.tab_main_content, mainFragments.get(i));
                }
                monitorUnitFragment.setCurrentDeviceID(deviceID);
                transaction.show(mainFragments.get(i));
                transaction.commit();
            } else {
                if (mainFragments.get(i).isAdded()) {
                    mainFragments.get(i).onResume();
                } else {
                    transaction.add(R.id.tab_main_content, mainFragments.get(i));
                }
                transaction.show(mainFragments.get(i));
                transaction.commit();
            }
        }
    }

    private void refreshButtonBackground(int i) {
        for (int j = 0; j < bt_list.size(); j++) {
            if (j == i) {
                bt_list.get(j).setBackgroundResource(R.drawable.btn_pressed);
            } else {
                if (bt_list.get(j).isEnabled()) {
                    bt_list.get(j).setBackgroundResource(R.drawable.btn_default);
                }
            }
        }
    }

    /*
         * 隐藏所有的Fragment
         * */
    private void hideFragment(FragmentTransaction transaction) {
        for (int i = 0; i < mainFragments.size(); i++) {
//            if (mainFragments.get(i).isAdded()) {
//                mainFragments.get(i).onResume();
//            } else {
//                transaction.add(R.id.tab_main_content, mainFragments.get(i));
//            }
            transaction.hide(mainFragments.get(i));
        }
    }

    @OnClick({R.id.bt_device_start, R.id.bt_reset, R.id.bt_home, R.id.bt_event, R.id.bt_debug, R.id.bt_set, R.id.bt_thd, R.id.bt_unit_1, R.id.bt_unit_2, R.id.bt_unit_3, R.id.bt_unit_4, R.id.bt_unit_5, R.id.bt_unit_6, R.id.bt_unit_7, R.id.bt_unit_8, R.id.bt_refresh_communicating, R.id.systemState})
    public void onViewClicked(View view) {
        for (int i = 0; i < bt_list.size(); i++) {
            if (view.getId() == bt_list.get(i).getId()) {
                setTable(i);
//                if (i == 2 | i == 3) {
//                    if (System.currentTimeMillis() - lastLoginTime > Constants.OUTLOGINTIME) {
//                        final int finalI = i;
//                        //输入密码
//                        MKeyBoard_NumberInput mKeyBoardInputValue = new MKeyBoard_NumberInput();
//                        mKeyBoardInputValue.setKeyBoardType(MKeyBoard_NumberInput.PSD);
//                        mKeyBoardInputValue.show(mainFragments.get(0).getFragmentManager(), "");
//                        mKeyBoardInputValue.setMkeyBoardListener(new MKeyBoard_NumberInput.MkeyBoardListener_numberKeyBoard() {
//                            @Override
//                            public void onClink(boolean isCorrect, String value) {
//                                if (isCorrect) {
//                                    setSelect(finalI);
//                                    lastLoginTime = System.currentTimeMillis();
//                                }
//                            }
//                        });
//                    } else {
//                        setSelect(i);
//                    }
//                } else {
//                    setSelect(i);
//                }

            }
        }
        switch (view.getId()) {
            case R.id.bt_refresh_communicating:
                showDiolg("是否刷新通信？");
                Dialog_Alert.setDiolgAlertListener(new Dialog_Alert.DialogAlertListener() {
                    @Override
                    public void onClink(boolean flag) {
                        if (flag) {
                            Toast.makeText(mContext, "正在刷新通信请稍后...", Toast.LENGTH_SHORT).show();
                            ModbusThread.refreshCommunicate();
                            LitePalHelper.insertOperateInfo("刷新通信");
                        }
                    }
                });
                break;
            case R.id.bt_reset:
                showDiolg("是否执行复位操作？");
                Dialog_Alert.setDiolgAlertListener(new Dialog_Alert.DialogAlertListener() {
                    @Override
                    public void onClink(boolean flag) {
                        if (flag) {
                            Toast.makeText(mContext, "正在复位请稍后...", Toast.LENGTH_SHORT).show();
                            Constants.writeDataModel.controlCommand = EnumDataHelper.EnumWriteData_Command.RESET;
                            CommunicateManager.sendData();
                            LitePalHelper.insertOperateInfo("复位操作");
                        }
                    }
                });
                break;
            case R.id.bt_device_start:
                showDiolg("是否执行" + bt_device_start.getText().toString() + "操作？");
                Dialog_Alert.setDiolgAlertListener(new Dialog_Alert.DialogAlertListener() {
                    @Override
                    public void onClink(boolean flag) {
                        if (flag) {
                            Toast.makeText(mContext, "正在执行请稍后...", Toast.LENGTH_SHORT).show();
                            if ("启动".equals(bt_device_start.getText().toString())) {
                                Constants.writeDataModel.controlCommand = EnumDataHelper.EnumWriteData_Command.STATR;
                                LitePalHelper.insertOperateInfo("下发启动命令");
                            } else {
                                Constants.writeDataModel.controlCommand = EnumDataHelper.EnumWriteData_Command.STOP;
                                LitePalHelper.insertOperateInfo("下发停机命令");
                            }
                            CommunicateManager.sendData();
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ModbusThread.isModbusThreadRunning = false;
        EventBus.getDefault().unregister(this);
    }

    //    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventCommunicateStateChange(String state) {
//        Toast.makeText(mContext, "通信状态改变-----", Toast.LENGTH_SHORT).show();
//        deviceCommunicateState = Constants.DEVICE_COMMUNICATE_STATE;
//        for (int i = 0; i < deviceCommunicateState.length; i++) {
//            if (deviceCommunicateState[i]) {
//                bt_list_unit.get(i).setBackgroundResource(R.drawable.btn_gray_radio);
//                bt_list_unit.get(i).setEnabled(false);
//            } else {
//                bt_list_unit.get(i).setBackgroundResource(R.drawable.btn_default);
//                bt_list_unit.get(i).setEnabled(true);
//            }
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveDeviceState(EventBus_int_bool eventBusIntBool) {
        int resourceID = eventBusIntBool.flag ? R.drawable.btn_default : R.drawable.btn_gray_radio;
        bt_list_unit.get(eventBusIntBool.id - 1).setBackgroundResource(resourceID);
        bt_list_unit.get(eventBusIntBool.id - 1).setEnabled(eventBusIntBool.flag);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getSystemTime(String systemTime) {
        tvSystemTime.setText(systemTime);
//        Toast.makeText(mContext, "", Toast.LENGTH_SHORT).show();
    }

    private void showDiolg(String commandName) {
        Dialog_Alert diolgAlert = new Dialog_Alert();
        diolgAlert.setCommandName(commandName);
        diolgAlert.show(mainFragments.get(0).getFragmentManager(), "");
    }

    private void showDiolg_PSD() {
        Dialog_Password dialog_password = new Dialog_Password();
        dialog_password.show(mainFragments.get(0).getFragmentManager(), "");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeButtonState(EventbusModel_setting_debug_state obj) {
        if (obj != null) {
            if (obj.flag) {
                systemState.setVisibility(View.VISIBLE);
            } else {
                systemState.setVisibility(View.INVISIBLE);
            }
        }
    }

    //判断 启动，复位按钮显示逻辑
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveCellsData(EventBus_showCells eventBusShowCells) {
        int mTotalCapacity = 0;
        Map<Integer, Cell_show> cell_showMap = eventBusShowCells.cell_showMap;
        ReceiveDataModel receiveDataModel = cells2ShowAdapter.cells2ReceiveDataModel(eventBusShowCells.cell_showMap);
        if (eventBusShowCells.deviceID == 1) {
            Log.e("unit_np1", "unit 1--" + receiveDataModel.grid_voltage_a + "---" + receiveDataModel.UdcP + "---" + receiveDataModel.UdcN);
        } else if (eventBusShowCells.deviceID == 6) {
            Log.e("unit_np6", "unit 6--" + receiveDataModel.grid_voltage_a + "---" + receiveDataModel.UdcP + "---" + receiveDataModel.UdcN);
        }

        receiveDataModelCurrentValue = receiveDataModel;
        Constants.deviceCapacity[eventBusShowCells.deviceID - 1] = Integer.valueOf(receiveDataModel.capacity);
        for (int capactiy : Constants.deviceCapacity) {
            mTotalCapacity = mTotalCapacity + capactiy;
            LogUtil.e("totalcapacity-i", "" + capactiy);
        }
        Constants.totalCapacity = mTotalCapacity;
        Constants.writeDataModel.totalCapacity = Constants.totalCapacity * 10;
        LogUtil.e("totalcapacity" + "" + Constants.writeDataModel.totalCapacity);

        if ("运行".equals(receiveDataModel.systemState) | "调试运行".equals(receiveDataModel.systemState)) {
            Constants.deviceStates[eventBusShowCells.deviceID - 1].deviceState = DeviceState.deviceState_running;
        } else if ("故障".equals(receiveDataModel.systemState)) {
            Constants.deviceStates[eventBusShowCells.deviceID - 1].deviceState = DeviceState.deviceState_error;
        } else if ("待机".equals(receiveDataModel.systemState)) {
            Constants.deviceStates[eventBusShowCells.deviceID - 1].deviceState = DeviceState.deviceState_waiting;
        }
        updateControlButtonsState();
//        updateUnitsState();
    }

    //todo 问题:多单元并联情况下,单元导航栏,出现灰色状态,----刷新结束后决定通信单元,之后不再更新,待修改
    private void updateUnitsState() {//根据通信状态首先确认按钮是否允许点击
        for (int i = 0; i < bt_list_unit.size(); i++) {
            if (Constants.deviceStates[i].isConnect) {
                if (Constants.deviceStates[i].enableState) {//enableSate,单元使能状态
                    bt_list_unit.get(i).setBackgroundResource(R.drawable.btn_pressed);

                } else {
                    bt_list_unit.get(i).setBackgroundResource(R.drawable.btn_default);
                }
                bt_list_unit.get(i).setEnabled(true);
            } else {
                bt_list_unit.get(i).setBackgroundResource(R.drawable.btn_gray);
                bt_list_unit.get(i).setEnabled(false);
            }
        }
    }

    private void updateControlButtonsState() {
        //按钮现实逻辑
        int runningCount = 0;
        int waitingCount = 0;
        int errorCount = 0;
        for (DeviceState deviceState :
                Constants.deviceStates) {
            if (deviceState.isConnect) {
                if (DeviceState.deviceState_running == deviceState.deviceState) {
                    runningCount++;
                } else if (DeviceState.deviceState_waiting == deviceState.deviceState) {
                    waitingCount++;
                } else if (DeviceState.deviceState_error == deviceState.deviceState) {
                    errorCount++;
                }
            }
        }
        if (runningCount == 0 && errorCount == 0 && waitingCount != 0) {
            //均为待机
            bt_device_start.setVisibility(View.VISIBLE);
            setButttonStyle(bt_device_start, R.drawable.start, R.drawable.green_btn_bg, R.color.green_color, "启动");
            btReset.setVisibility(View.INVISIBLE);
            Constants.startButtonState = 1;
            EventbusModel_debugButton_state eventbusModel_debugButton_state = new EventbusModel_debugButton_state();
            eventbusModel_debugButton_state.isShow = true;
            eventbusModel_debugButton_state.state = EventbusModel_debugButton_state.DEBUG_START;
            EventBus.getDefault().post(eventbusModel_debugButton_state);
        } else if (waitingCount == 0 && runningCount == 0 && errorCount != 0) {
            //均为故障
            bt_device_start.setVisibility(View.INVISIBLE);
            btReset.setVisibility(View.VISIBLE);
            btReset.setText("复位");
            Constants.startButtonState = 0;
            EventbusModel_debugButton_state eventbusModel_debugButton_state = new EventbusModel_debugButton_state();
            eventbusModel_debugButton_state.isShow = false;
            eventbusModel_debugButton_state.state = EventbusModel_debugButton_state.DEBUG_START;
            EventBus.getDefault().post(eventbusModel_debugButton_state);

        } else if (runningCount == 0 && waitingCount != 0 && errorCount != 0) {
            //部分待机，部分故障
            bt_device_start.setVisibility(View.VISIBLE);
            setButttonStyle(bt_device_start, R.drawable.start, R.drawable.green_btn_bg, R.color.green_color, "启动");
            btReset.setVisibility(View.VISIBLE);
            btReset.setText("复位");
            Constants.startButtonState = 1;
            EventbusModel_debugButton_state eventbusModel_debugButton_state = new EventbusModel_debugButton_state();
            eventbusModel_debugButton_state.isShow = true;
            eventbusModel_debugButton_state.state = EventbusModel_debugButton_state.DEBUG_START;
            EventBus.getDefault().post(eventbusModel_debugButton_state);
        } else if (runningCount != 0) {
            //至少一个单元运行
            bt_device_start.setVisibility(View.VISIBLE);
            setButttonStyle(bt_device_start, R.drawable.stop, R.drawable.red_btn_bg, R.color.red_color, "停机");
            btReset.setVisibility(View.INVISIBLE);
            Constants.startButtonState = 2;
            EventbusModel_debugButton_state eventbusModel_debugButton_state = new EventbusModel_debugButton_state();
            eventbusModel_debugButton_state.isShow = true;
            eventbusModel_debugButton_state.state = EventbusModel_debugButton_state.DEBUG_STOP;
            EventBus.getDefault().post(eventbusModel_debugButton_state);
        } else {
            bt_device_start.setVisibility(View.INVISIBLE);
            btReset.setVisibility(View.INVISIBLE);
            Constants.startButtonState = 0;
            EventbusModel_debugButton_state eventbusModel_debugButton_state = new EventbusModel_debugButton_state();
            eventbusModel_debugButton_state.isShow = false;
            eventbusModel_debugButton_state.state = EventbusModel_debugButton_state.DEBUG_STOP;
            EventBus.getDefault().post(eventbusModel_debugButton_state);

        }
    }

    private void setButttonStyle(Button bt, int leftPicture, int background, int textColor, String text) {
        Drawable drawable = getResources().getDrawable(leftPicture);
        bt.setBackgroundResource(background);
        bt.setTextColor(getResources().getColor(textColor));
        bt.setText(text);
        bt.setPadding(9, 0, 0, 0);
/// 这一步必须要做,否则不会显示.
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        bt.setCompoundDrawables(drawable, null, null, null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
//如果登陆时间和最后操作时间时间间隔相差10min之内，登陆时间改为最后操作时间
        if (System.currentTimeMillis() - lastLoginTime < Constants.OUTLOGINTIME) {
            lastLoginTime = System.currentTimeMillis();
        }
        return super.onTouchEvent(event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEventTag(EventbusModel_Tag eventbusModel_tag) {
        if (EventbusModel_Tag.FRAGMENT_GOTO_1.equals(eventbusModel_tag.tag)) {
            setSelect(1);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventBusTost(EventbusModel_Toast eventbusModel_toast) {
        Toast.makeText(MyApplication.getContext(), eventbusModel_toast.context, Toast.LENGTH_SHORT).show();
    }


    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventSaveReportData(ReportDateModel reportDateModel) {
        //处理任务
        //判断当前是否正常通信---
        //查数据（实时数据 ， 最终结果数据）
        //当前值 对比 ，更新数据库


    }
}
